import controller.base
import datetime


class PatientHandler(controller.base.AuthHandler):
    def post(self):
        cId = self.get_body_para("cId")
        name = self.get_body_para("name")
        gender = self.get_body_para("gender")
        avatar = self.get_body_para("avatar")
        birth = self.get_body_para("dateOfBirth")
        if avatar is None:
            avatar = ""

        if cId is None or name is None or gender is None or birth is None:
            self.rsp(7, msg="parameter error")
            return

        sql = 'SELECT * FROM patients WHERE cid = %s AND doctor = %s'
        res = self.db.query(sql, cId, self.user["id"])
        if res:
            self.rsp(6, msg="cId used")
            return

        sql = "INSERT INTO patients (doctor,cid,name,gender,avatar,birthday,createTime) VALUES (%s,%s,%s,%s,%s,%s,%s)"
        res = self.db.insert(sql, self.user["id"], cId, name, gender, avatar, birth, datetime.datetime.now().strftime("%y-%m-%d %H:%M:%S"))
        data = {
            "patients": {
                    "id": res,
                    "cId": cId,
                    "name": name,
                    "gender": gender,
                    "avatar": avatar,
                    "dateOfBirth": birth
            }
        }
        self.rsp(code=0, data=data)

    def put(self, patient_id):
        id = patient_id
        cId = self.get_body_para("cId")
        name = self.get_body_para("name")
        gender = self.get_body_para("gender")
        avatar = self.get_body_para("avatar")
        birth = self.get_body_para("dateOfBirth")
        if avatar is None:
            avatar = ""

        if cId is None or name is None or gender is None or birth is None:
            self.rsp(7, msg="parameter error")
            return

        sql = 'SELECT * FROM patients WHERE id = %s'
        res = self.db.get(sql, id)
        if res is None:
            self.rsp(6, msg="patient not exist")
            return

        if res['doctor'] != self.user["id"]:
            self.rsp(9, msg="not your patient")
            return

        sql = "UPDATE patients SET cid = %s, name = %s, gender = %s, avatar = %s, birthday = %s " \
              "WHERE id = %s"

        res = self.db.update(sql, cId, name, gender, avatar, birth, id)
        data = {
            "patients": [
                {
                    "id": id,
                    "cId": cId,
                    "name": name,
                    "gender": gender,
                    "avatar": avatar,
                    "dateOfBirth": birth
                }
            ],
        }
        self.rsp(code=0, data=data)

    def delete(self, patient_id):
        id = patient_id
        sql = 'SELECT * FROM patients WHERE id = %s'
        res = self.db.get(sql, id)
        if res is None:
            self.rsp(6, msg="patient not exist")
            return
        if res['doctor'] != self.user["id"]:
            self.rsp(9, msg="not your patient")
            return
        sql = 'DELETE FROM patients WHERE  id = %s'
        res = self.db.execute(sql, id)
        self.rsp(code=0)

    def get(self):
        page = self.get_query_argument('page', default=None)
        if page is not None:
            page = int(page)
        if (page is not None) and page <=  0:
            self.rsp(6, msg="page starts from 1")
            return
        sql = 'SELECT * FROM patients WHERE doctor = %s'
        res = self.db.query(sql, self.user["id"])
        if res is None:
            self.rsp(6, msg="no patient exist")
            return
        length = len(res)

        start = 0
        end = length
        hasMore = False
        if page is not None:
            start = 20 * (page - 1)
            end = 20 * page
            if start > (length - 1):
                self.rsp(6, msg="page out of range")
                return
            if end >= length:
                end = length
            else:
                hasMore = True
        patients = []
        for idx in range(start, end):
            patient = res[idx]
            patients.append({
                    "id": patient['id'],
                    "cId": patient['cid'],
                    "name": patient['name'],
                    "gender": patient['gender'],
                    "avatar": patient['avatar'],
                    "dateOfBirth": patient['birthday'].strftime("%Y-%m-%d %H:%M:%S")
                })
        data = {"patients": patients, "hasMore": hasMore}
        self.rsp(code=0, data=data)
